package com.jet.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jet.merchant.domain.entity.MerchantRegion;
import com.jet.merchant.domain.vo.RegionPathVo;
import com.jet.merchant.domain.vo.RegionTreeVo;
import com.jet.merchant.mapper.MerchantRegionMapper;
import com.jet.merchant.service.IMerchantRegionService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-14
 */
@Service
public class MerchantRegionServiceImpl extends ServiceImpl<MerchantRegionMapper, MerchantRegion> implements IMerchantRegionService {

    @Override
    public List<RegionTreeVo> findAll() {
        Wrapper<MerchantRegion> wrapper = new LambdaQueryWrapper<MerchantRegion>()
                .lt(MerchantRegion::getLevel, 4);
        List<MerchantRegion> list = super.list(wrapper);
        return child("0", list);
    }

    private List<RegionTreeVo> child(String pid, List<MerchantRegion> list) {
        List<MerchantRegion> regions = list.stream()
                .filter(y -> y.getPid().equals(pid)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(regions)) {
            return null;
        }
        return regions.stream().map(region -> {
            RegionTreeVo vo = new RegionTreeVo();
            vo.setValue(region.getId());
            vo.setLabel(region.getName());
            vo.setChildren(child(region.getId(), list));
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public RegionPathVo findById(String id) {
        MerchantRegion region = super.getById(id);
        if (region == null) {
            return null;
        }
        RegionPathVo vo = new RegionPathVo();
        vo.setId(id);
        String[] ids = region.getIdPath().split(",");
        String[] names = region.getNamePath().split(",");
        if (ids.length > 0) {
            vo.setProvince(ids[0]);
            vo.setProvinceName(names[0]);
        }
        if (ids.length > 1) {
            vo.setCity(ids[1]);
            vo.setCityName(names[1]);
        }
        if (ids.length > 2) {
            vo.setArea(ids[2]);
            vo.setAreaName(names[2]);
        }
        return vo;
    }
}
